var isUsernameOK = false;
var isPassword1OK = false;
var isPassword2OK = false;
var isDisplayNameOK = false;

/*****************************************************************************
 * 
 * INIT FORM FUNCTIONS
 * 
 *****************************************************************************/

function initLogin(){
    document.forms[0].username.focus();
}

function initRegistration(){
    document.forms[0].username.focus();
    document.getElementById("btnRegister").disabled = true;
    
    showUsernameFormatError(false);
    
    hideHint("passwordHint");
    hideHint("displayNameHint");
}



/*****************************************************************************
 * 
 *                          FOCUS GAINED/LOST FUNCTIONS
 * 
 *****************************************************************************/

function blurUsername(){
    var usernameValue = document.forms[0]["username"].value;
    
    if(usernameValue.length < 1){
	//show required field error
	showRequiredFieldError("username");
	hideValidIcon("username");
	isUsernameOK = false;
	
    }else if(!isUsernameValidFormat(usernameValue)){
	//show invalid format error
	showInvalidFieldError("username");
	hideValidIcon("username");
	isUsernameOK = false;
    }else{
	//no error
	showValidIcon("username");
	hideInvalidFieldError("username");
	hideRequiredFieldError("username");
	
	isUsernameOK = true;
	checkFormReady();
    }
    
    hideHint("username");
}

function focusUsername(){
    showHint("username");
    hideValidIcon("username");
    hideRequiredFieldError("username");
    hideInvalidFieldError("username");
}

function blurPassword1(){
    var password1 = document.forms[0]["password1"].value;
    
    /*
     * at least eight characters long; 
     * has at least one lowercase, uppercase, numeric, and special character; 
     * doesn't include the words "password", "pwd"; 
     * and doesn't include an alphanumeric sequence four or more characters in length (e.g. "1234")
     */
    
    var isValid = isPasswordValid(password1, {
	length:   [8, Infinity],
	lower:    1,
	upper:    1,
	numeric:  1,
	special:  1,
	badWords: ["password", "pwd"],
	badSequenceLength: 4
    });
    
    if(password1.length < 1){
	showRequiredFieldError("password1");
    }else if(!isValid){
	//show invalid password format error
	showInvalidFieldError("password1");
	hideValidIcon("password1");
	isPassword1OK = false;
    }else{
	//password ok
	showValidIcon("password1");
	hideInvalidFieldError("password1");
	hideRequiredFieldError("password1");
	
	isPassword1OK = true;
	checkFormReady();
    }
    hideHint("password1");
}

function focusPassword1(){
    showHint("password1");
    hideValidIcon("password1");
    hideRequiredFieldError("password1");
    hideInvalidFieldError("password1");
}

function blurPassword2(){
    var password1 = document.forms[0]["password1"].value;
    var password2 = document.forms[0]["password2"].value;
    
    if(password2.length < 1){
	showRequiredFieldError("password2");
    }else if(!isPasswordMatch(password1, password2)){
	//passwords don't match
	showInvalidFieldError("password2");
	hideValidIcon("password2");
	isPassword2OK = false;
    }else{
	//password ok
	showValidIcon("password2");
	hideInvalidFieldError("password2");
	hideRequiredFieldError("password2");
	
	isPassword2OK = true;
	checkFormReady();
    }
    hideHint("password2");
    
}

function focusPassword2(){
    showHint("password2");
    hideValidIcon("password2");
    hideRequiredFieldError("password2");
    hideInvalidFieldError("password2");
}

function blurDisplayName(){
    var displayName = document.forms[0]["displayName"].value;
    
    if(displayName.length < 1){
	showRequiredFieldError("displayName");
	
    }else{
	showValidIcon("displayName");
	isDisplayNameOK = true;
	checkFormReady();
	
    }
    hideHint("displayName");
	
    
}

function focusDisplayName(){
    showHint("displayName");
    hideValidIcon("displayName");
    hideRequiredFieldError("displayName");
    hideInvalidFieldError("displayName");
}
	    
function showUsernameFormatError(show){
    if(show){
	document.getElementById("usernameFormatError").style.display = "block";
    }else{
	document.getElementById("usernameFormatError").style.display = "none";
    }
		
}


/*****************************************************************************
 * 
 *                      FORM COMPLETE FUNCTIONS
 * 
 *****************************************************************************/

function checkFormReady(){
    if(isUsernameOK && isPassword1OK && isPassword2OK && isDisplayNameOK){
	document.getElementById("btnRegister").disabled = false;
    }
}

/*****************************************************************************
 * 
 *                      FIELD VALIDATION FUNCTIONS
 * 
 *****************************************************************************/
	    
function  isUsernameValidFormat(usernameValue)
{    
    var atpos = usernameValue.indexOf("@");
    var dotpos = usernameValue.lastIndexOf(".");
    
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= usernameValue.length)
    {
	//invalid format
	return false;
    }else{
	//valid format
	return true;
    }
}

function isPasswordMatch(password1, password2){
    if(password1 == password2){
	return true;
    }else{
	return false;
    }
}

function isPasswordValid(pw, options){
    
    /*
     * Password Validator 0.1
     * (c) 2007 Steven Levithan <stevenlevithan.com>
     * MIT License
     * http://blog.stevenlevithan.com/archives/javascript-password-validator
     */
	
    
    // default options (allows any password)
    var o = {
	lower:    0,
	upper:    0,
	alpha:    0, /* lower + upper */
	numeric:  0,
	special:  0,
	length:   [0, Infinity],
	custom:   [ /* regexes and/or functions */ ],
	badWords: [],
	badSequenceLength: 0,
	noQwertySequences: false,
	noSequential:      false
    };

    for (var property in options)
	o[property] = options[property];

    var	re = {
	lower:   /[a-z]/g,
	upper:   /[A-Z]/g,
	alpha:   /[A-Z]/gi,
	numeric: /[0-9]/g,
	special: /[\W_]/g
    },
    rule, i;

    // enforce min/max length
    if (pw.length < o.length[0] || pw.length > o.length[1])
	return false;

    // enforce lower/upper/alpha/numeric/special rules
    for (rule in re) {
	if ((pw.match(re[rule]) || []).length < o[rule])
	    return false;
    }

    // enforce word ban (case insensitive)
    for (i = 0; i < o.badWords.length; i++) {
	if (pw.toLowerCase().indexOf(o.badWords[i].toLowerCase()) > -1)
	    return false;
    }

    // enforce the no sequential, identical characters rule
    if (o.noSequential && /([\S\s])\1/.test(pw))
	return false;

    // enforce alphanumeric/qwerty sequence ban rules
    if (o.badSequenceLength) {
	var	lower   = "abcdefghijklmnopqrstuvwxyz",
	upper   = lower.toUpperCase(),
	numbers = "0123456789",
	qwerty  = "qwertyuiopasdfghjklzxcvbnm",
	start   = o.badSequenceLength - 1,
	seq     = "_" + pw.slice(0, start);
	for (i = start; i < pw.length; i++) {
	    seq = seq.slice(1) + pw.charAt(i);
	    if (
		lower.indexOf(seq)   > -1 ||
		upper.indexOf(seq)   > -1 ||
		numbers.indexOf(seq) > -1 ||
		(o.noQwertySequences && qwerty.indexOf(seq) > -1)
		) {
		return false;
	    }
	}
    }

    // enforce custom regex/function rules
    for (i = 0; i < o.custom.length; i++) {
	rule = o.custom[i];
	if (rule instanceof RegExp) {
	    if (!rule.test(pw))
		return false;
	} else if (rule instanceof Function) {
	    if (!rule(pw))
		return false;
	}
    }

    // great success!
    return true;
}

/*****************************************************************************
 * 
 *                  REQUIRED FIELDS SHOW/HIDE FUNCTIONS
 * 
 *****************************************************************************/


function showRequiredFieldError(field){
    document.getElementById(field + "RequiredError").style.display = "inline";
}

function hideRequiredFieldError(field){
    document.getElementById(field + "RequiredError").style.display = "none";
}

/*****************************************************************************
 * 
 *                  INVALID FIELD ERROR SHOW/HIDE FUNCTIONS
 * 
 *****************************************************************************/

function showInvalidFieldError(field){
    document.getElementById(field + "InvalidError").style.display = "block";
}

function hideInvalidFieldError(field){
    document.getElementById(field + "InvalidError").style.display = "none";
}

/*****************************************************************************
 * 
 *                        HINT SHOW/HIDE FUNCTIONS
 * 
 *****************************************************************************/

function showHint(control){
    document.getElementById(control + "Hint").style.display = "block";
}

function hideHint(control){
    document.getElementById(control + "Hint").style.display = "none";
}

/*****************************************************************************
 * 
 *                        VALID FIELD ICON SHOW/HIDE FUNCTIONS
 * 
 *****************************************************************************/

function showValidIcon(control){
    document.getElementById(control + "ValidIcon").style.display = "inline";
}

function hideValidIcon(control){
    document.getElementById(control + "ValidIcon").style.display = "none";
}